package dtaskboard.client.toolbar;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dtaskboard.client.Constants;
import dtaskboard.client.DialogUtil;
import dtaskboard.client.service.LoginService;
import dtaskboard.client.service.LoginServiceAsync;

public class CreateUserDialog extends DialogBox {

  private final TextBox username;
  private final TextBox password;
  private final TextBox name;

  public CreateUserDialog() {
    this.username = new TextBox();
    this.password = new TextBox();
    this.name = new TextBox();
    Panel panel = new VerticalPanel();

    Label userLabel = new Label("Usuario");
    Label passLabel = new Label("Senha");
    Label nameLabel = new Label("Nome");

    panel.add(userLabel);
    panel.add(this.username);
    panel.add(passLabel);
    panel.add(this.password);
    panel.add(nameLabel);
    panel.add(this.name);
    panel.add(new CreateUserSubmitButton());

    super.setAnimationEnabled(true);
    super.setAutoHideEnabled(true);
    super.setHTML("Criação de usuario");
    super.setGlassEnabled(true);
    super.setModal(true);
    super.setWidget(panel);
    super.setVisible(true);
  }

  @Override
  public void show() {
    this.username.setText("");
    this.password.setText("");
    this.name.setText("");
    super.show();
  }

  class CreateUserSubmitButton extends Button {
    public CreateUserSubmitButton() {
      this.setText("Cria usuario");
      this.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          LoginServiceAsync loginService = GWT.create(LoginService.class);
          final CreateUserDialog cud = CreateUserDialog.this;
          String sessionId = Cookies.getCookie(Constants.sessionIdCookie);
          loginService.saveUser(cud.username.getText(), cud.password.getText(),
              cud.name.getText(), sessionId, new AsyncCallback<Void>() {

                @Override
                public void onSuccess(Void result) {
                  DialogUtil.closableDialog("Criação de usuario",
                      "Usuario criado com sucesso");
                  cud.hide();
                }

                @Override
                public void onFailure(Throwable caught) {
                  DialogUtil.closableDialog("Erro",
                      "Nao foi possivel criar o usuario.");
                }
              });
        }
      });
    }
  }

}
